﻿Ext.define('app.prm.document.Index', {
    extend: 'Ext.panel.Panel',
    layout: 'border',
    projectId: 0,
    controller: 'document',
    requires: ['app.prm.document.DocumentController', 'app.prm.document.ViewModel'],
    viewModel: {
        type: 'documentModel'
    },
    initComponent: function () {
        var me = this;
        me.projectId = me.paramsId;

        me.items = [
            me.getTabPanel(),
            me.getCenter()
        ];
        me.callParent();
    },
    listeners: {
        afterrender: 'onInit'
    },
    getCenter: function () {
        var me = this;
        if (!this.centerPanel) {
            this.centerPanel = new Ext.panel.Panel({
                region: 'center',
                layout: 'fit',
                items: [me.getGrid()]
            });
        }
        return this.centerPanel;
    },
    getTabPanel: function () {
        var me = this;
        if (!this.tagPanel) {
            me.tagStore = Ext.create("app.ux.PrmStore", { url: '/api/services/app/document/GetDocumentTag?projectId=' + me.projectId });
            var tagColud = Ext.create("app.ux.TagCloud",
                {
                    displayWeight: true,
                    displayField: 'key',
                    weightField: 'value',
                    listeners: {
                        tagselect: function (tagcloud, record) {
                            var createId = record.data.createId;
                            var tag = record.data.key;
                            if (createId > 0) {
                                tag = "";
                            }
                            me.getTagGrid().store.filter = { typeId: 0, projectId: me.projectId, isDelete: false, createId: createId, tag: tag, hasAuth: false };
                            me.getTagGrid().store.load();
                        }
                    }
                });
            tagColud.setStore(me.tagStore);
            this.tagPanel = new Ext.tab.Panel({
                region: 'west',
                width: 320,
                deferredRender: false,
                split: true,
                items: [
                    {
                        title: '产出文档',
                        layout: 'fit',
                        items: [me.getTree()]
                    },
                    {
                        title: '项目附件',
                        items: [tagColud]
                    }
                ],
                listeners: {
                    tabchange: function (tabPanel, newCard, oldCard, eOpts) {
                        me.getCenter().removeAll(false);
                        if (newCard.title == '产出文档') {
                            me.getCenter().add(me.getGrid());
                        }
                        else {
                            me.getCenter().add(me.getTagGrid());
                        }
                    }
                }
            });
        }
        return this.tagPanel;
    },
    getTree: function () {
        var me = this;
        if (!this.tree) {
            this.tree = new Ext.tree.Panel({
                border: false,
                tbar: [{
                    text: '设置上传类型', bind: { hidden: '{!hasSetType}' }, icon: '/Content/images/edit.gif', handler: function () {
                        var win = Ext.create("app.prm.document.SetUploadType", { projectId: me.projectId });
                        win.on("savesuccess", function () {
                            me.getTree().store.load({
                                callback: function () {
                                    me.getTree().expandAll();
                                }
                            });
                            win.close();
                        });
                        win.show();
                    }
                },
                {
                    text: '回收站',
                    bind: { hidden: '{!hasTrash}' },
                    icon: '/Content/images/trash.gif',
                    handler: 'onOpenTrash'
                },
                    '->',

                {
                    text: '刷新', glyph: 0xf021,
                    handler: function () {
                        me.getTree().store.load({
                            callback: function () {
                                me.getTree().expandAll();
                            }
                        });
                    }
                }

                ],
                // title: '文档类型',
                useArrows: true,
                rootVisible: false,
                columns: [{
                    xtype: 'treecolumn',
                    text: '名称',
                    width: 250,
                    sortable: true,
                    dataIndex: 'text'
                }, {
                    text: '上传个数',
                    dataIndex: 'defaultUploadNum',
                    sortable: true,
                    renderer: function (val, meta, record) {
                        if (record.get('uploadedNum') > -1) {
                            return record.get('uploadedNum') + '/' + val;
                        }
                        return "";
                    }
                }],
                store: new Ext.data.TreeStore({
                    root: {
                        expanded: true
                    },
                    autoLoad: true,
                    nodeParam: 'parentId',
                    // 根节点的参数值是0
                    defaultRootId: "0",
                    proxy: {
                        type: 'ajax',
                        reader: {
                            type: 'json',
                            rootProperty: function (node) {
                                return node.result || node.children;
                            }
                        },
                        url: '/api/services/app/document/GetProjectDocumentTree?projectId=' + me.projectId
                    }
                }),
                root: { id: '0', text: 'text' },
                listeners: {
                    afterrender: function (tree) {

                        tree.expandAll();
                    },
                    select: 'onTreeSelect'
                }
            });
        }
        return this.tree;
    },
    getSearchField: function () {
        if (!this.searchField) {
            this.searchField = new Ext.form.field.Text({
                width: 250
            });
        }
        return this.searchField;
    },
    getGrid: function () {
        var me = this;
        if (!this.grid) {

            var gridStore = Ext.create("app.ux.PagePrmStore", {
                url: '/api/services/app/document/GetDocument',

                autoLoad: false, remoteSort: false,
                listeners: {
                    beforeload: function (store, opt, eopt) {
                        var sort = [];
                        if (opt._sorters && opt._sorters[0]._id && opt._sorters[0]._direction) {
                            for (var i = 0; i < opt._sorters.length; i++) {
                                var sorter = opt._sorters[i];
                                sort.push(sorter._id + " " + sorter._direction);
                            }
                        } else {
                            sort.push("id DESC");
                        }
                        var filter = store.filter;
                        filter.Sorting = sort.toString();
                        filter.SkipCount = opt._start;
                        filter.MaxResultCount = opt._limit;
                        store.proxy.extraParams = filter;
                    }
                },
                sorters: [{
                    //先按年龄降序  
                    property: 'reportDate',
                    direction: 'DESC'
                },
                {
                    //先按年龄降序  
                    property: 'id',
                    direction: 'DESC'
                }]
            });
            this.gridbbar = Ext.create({
                xtype: 'pagingtoolbar',
                store: gridStore,   // same store GridPanel is using
                dock: 'bottom',
                displayInfo: true
            });

            this.grid = new Ext.grid.Panel({
                title: '文档列表',
                border: false,
                tbar: [
                    {
                        text: '删除',
                        iconCls: 'delete',
                        bind: { hidden: '{hasDelete}' },
                        handler: function () {

                            var selections = me.grid.getSelection();
                            if (selections.length > 0) {

                                Ext.Msg.confirm("警告", "确定删除么？", function (btn) {
                                    if (btn == 'yes') {
                                        var delFiles = [];
                                        for (var i = 0; i < selections.length; i++) {
                                            var r = selections[i];
                                            delFiles.push(r.data.id);
                                        }

                                        App.AjaxPost('/api/services/app/document/ERemoveDocuments', delFiles, function (data) {
                                            me.loadGrid();
                                        });

                                    }
                                })


                            }
                        }
                    },
                    {
                        text: '下载',
                        iconCls: 'download',
                        bind: { hidden: '{hasDownload}' },
                        handler: function () {
                            var selections = me.grid.getSelection();
                            if (selections.length > 0) {
                                var downloadUrl = [];
                                for (var i = 0; i < selections.length; i++) {
                                    var r = selections[i];
                                    downloadUrl.push('/api/services/app/document/GetFile?path=' + r.data.fullUrl);
                                }
                                $(downloadUrl).multiDownload();

                            }


                        }
                    },
                    '-',
                    "文档名称：",
                    me.getSearchField(),
                    {
                        xtype: 'button',
                        text: '查询',
                        handler: function () {
                            me.loadGrid();
                        }
                    },
                    "->",
                    {
                        text: '上传',
                        icon: '/Content/images/add.png',
                        bind: { hidden: '{hasUpload}' },
                        handler: function () {
                            var node = me.getTree().getSelection()[0];
                            if (!node) {
                                Ext.Msg.alert('系统提示', '请选择文档类型');
                                return false;
                            }
                            var componentType = 'app.prm.document.UploadFile';
                            var multipleFiles = me.getViewModel().data.multipleFiles;
                            if (multipleFiles) {
                                componentType = 'app.prm.document.MultipleUploadFile';
                            }
                            var id = node.data.id;
                            var __index = id.indexOf('_');
                            var __length = id.length;
                            var stepname = '';
                            if (__index > 0) {
                                stepname = id.substring(__index + 1);
                                id = id.substring(0, __index);
                            }

                            var win = Ext.create(componentType, { ProjectId: me.projectId, TypeId: id, stepname: stepname });
                            win.on("savesuccess", function () {
                                me.loadGrid();
                                win.close();
                            });
                            win.show();
                        }
                    }
                ],
                viewConfig: {
                    enableTextSelection: true //可以复制单元格文字
                },
                forceFit: true,
                store: gridStore,
                selModel: {
                    selType: 'checkboxmodel'
                },

                columns: [
                    {
                        text: "#", xtype: 'rownumberer', width: 50
                    },
                    {
                        header: "名称", dataIndex: 'name', width: 200
                    },
                    { header: "大小(kb)", dataIndex: 'length' },
                    { header: "类型", dataIndex: 'extension', hidden: true },
                    {
                        header: "版本", dataIndex: 'versionNo', renderer: function (value, p, record) {
                            return value.toFixed(2);
                        }
                    }, {
                        header: "报告时间", dataIndex: 'reportDate', renderer: function (value, p, record) {
                            return Ext.util.Format.date(value, 'Y-m-d');
                        }
                    },
                    {
                        header: "创建时间", dataIndex: 'creationTime', hidden: true, renderer: function (value, p, record) {
                            return Ext.util.Format.date(value, 'Y-m-d');
                        }
                    },
                    {
                        header: "创建人", dataIndex: 'creationUser'
                    },
                    {
                        xtype: 'actioncolumn',
                        minWidth: 120,
                        header: '操作',
                        items: [
                            {
                                iconCls: 'edit',
                                tooltip: '上传文档',
                                handler: function (grid, rowIndex, colIndex) {
                                    var record = grid.store.getAt(rowIndex);
                                    if (!record.data.hasEdit) {
                                        return false;
                                    }
                                    var win = Ext.create("app.prm.document.Edit", { documentId: record.data.id });
                                    win.on("savesuccess", function () {
                                        me.loadGrid();
                                        win.close();
                                    });
                                    win.show();
                                },
                                getClass: function (v, meta, record) {
                                    if (record.data.hasEdit) {
                                        return 'edit';
                                    } else {
                                        return 'x-hidden';
                                    }
                                }
                            }, {
                                iconCls: 'share',
                                tooltip: '文档分享',
                                handler: function (grid, rowIndex, colIndex) {
                                    var record = grid.store.getAt(rowIndex);
                                    if (!record.data.hasEdit) {
                                        return false;
                                    }
                                    var win = Ext.create("app.prm.document.ShareDoc", { docId: record.data.id, projectId: me.projectId });
                                    win.show();
                                },
                                getClass: function (v, meta, record) {
                                    if (record.data.hasShare) {
                                        if (record.data.hasShared) {
                                            return 'shared';
                                        } else {
                                            return 'share';
                                        }
                                    } else {
                                        return 'x-hidden';
                                    }
                                }
                            },
                            {
                                iconCls: 'fixedVersion',
                                tooltip: '文档定版',
                                handler: function (grid, rowIndex, colIndex) {
                                    var store = grid.store;
                                    var record = store.getAt(rowIndex);
                                    if (!record.data.hasFixedVersion || record.data.isFixedVersion) {
                                        return false;
                                    }
                                    Ext.Msg.confirm('系统提示', '确定要定版文档吗？', function (btn) {
                                        if (btn == 'yes') {
                                            App.AjaxGet('/api/services/app/document/GetFixedVersion?documentId=' + record.data.id, function (data) {
                                                Ext.Msg.alert('系统提示', "定版成功");
                                                store.reload();
                                            });
                                        }
                                    });
                                },
                                getClass: function (v, meta, record) {
                                    if (record.data.hasFixedVersion && !record.data.isFixedVersion) {
                                        return 'fixedVersion';
                                    } else {
                                        return 'x-hidden';
                                    }
                                }
                            },
                            {
                                iconCls: 'bookopen',
                                tooltip: '查看版本',
                                handler: function (grid, rowIndex, colIndex) {
                                    var record = grid.store.getAt(rowIndex);
                                    if (!record.data.hasViewVersion) {
                                        return false;
                                    }
                                    var win = Ext.create("app.prm.document.Version", { documentId: record.data.id });
                                    win.show();
                                },
                                getClass: function (v, meta, record) {
                                    if (record.data.hasViewVersion) {
                                        return 'bookopen';
                                    } else {
                                        return 'x-hidden';
                                    }
                                }
                            },

                            {
                                iconCls: 'search',
                                tooltip: '预览',
                                handler: function (grid, rowIndex, colIndex) {
                                    var record = grid.store.getAt(rowIndex);
                                    if (!record.data.hasDownLoad) {
                                        return false;
                                    }


                                    window.open('/api/services/app/document/GetFileView?path=' + record.data.fullUrl);

                                },
                                getClass: function (v, meta, record) {
                                    if (record.data.hasDownLoad && record.get('name').toLowerCase().indexOf('pdf') > 0) {
                                        return 'search';
                                    } else {
                                        return 'x-hidden';
                                    }
                                }
                            },
                            //{
                            //    iconCls: 'download',
                            //    tooltip: '下载',
                            //    handler: function (grid, rowIndex, colIndex) {
                            //        var record = grid.store.getAt(rowIndex);
                            //        if (!record.data.hasDownLoad) {
                            //            return false;
                            //        }
                            //        {
                            //            window.location.href = '/api/services/app/document/GetFile?path=' + record.data.fullUrl;
                            //        }

                            //        //App.AjaxGet('/api/services/app/document/GetFile?path=' + record.data.fullUrl, function ()
                            //        //{

                            //        //});
                            //    },
                            //    getClass: function (v, meta, record) {
                            //        if (record.data.hasDownLoad) {
                            //            return 'download';
                            //        } else {
                            //            return 'x-hidden';
                            //        }
                            //    }
                            //},
                            //{
                            //    iconCls: 'delete',
                            //    tooltip: '删除文档',
                            //    handler: function (grid, rowIndex, colIndex) {
                            //        var record = grid.store.getAt(rowIndex);
                            //        if (!record.data.hasDelete) {
                            //            return false;
                            //        }
                            //        App.AjaxDelete('/api/services/app/document/RemoveDocument?documentId=' + record.data.id + "&projectId=" + me.projectId, function () {
                            //            me.loadGrid();
                            //        });
                            //    },
                            //    getClass: function (v, meta, record) {
                            //        if (record.data.hasDelete && !record.data.isDelete) {
                            //            return 'delete';
                            //        } else {
                            //            return 'x-hidden';
                            //        }
                            //    }
                            //},
                            {
                                iconCls: 'text_list_bullets',
                                tooltip: '操作日志',
                                handler: function (grid, rowIndex, colIndex) {
                                    var record = grid.store.getAt(rowIndex);
                                    var win = Ext.create("app.prm.document.DocumentLog", { title: '文档日志', documentId: record.data.id });
                                    win.show();
                                },
                                getClass: function (v, meta, record) {
                                    if (record.data.hasLogView) {
                                        return 'text_list_bullets';
                                    } else {
                                        return 'x-hidden';
                                    }
                                }
                            }
                        ]
                    }
                ],
                dockedItems: [this.gridbbar]
            });
        }
        return this.grid;
    },
    getTagGrid: function () {
        var me = this;
        if (!this.tagGrid) {
            var store = Ext.create("app.ux.PagePrmStore",
                {
                    url: '/api/services/app/document/GetDocument',
                    filter:
                    { typeId: 0, projectId: me.projectId, isDelete: false, hasAuth: false }
                });


            this.tagGridbbar = Ext.create({
                xtype: 'pagingtoolbar',
                store: store,   // same store GridPanel is using
                dock: 'bottom',
                displayInfo: true
            });
            this.tagGrid = new Ext.grid.Panel({
                title: '文档列表',
                region: 'center',
                border: false,
                tbar: [
                    {
                        text: '显示所有', glyph: 0xf021,
                        handler: function () {
                            me.getTagGrid().store.filter = { typeId: 0, projectId: me.projectId, isDelete: false, hasAuth: false };
                            me.getTagGrid().store.load();
                        }
                    },
                    "->",
                    {
                        text: '上传',
                        icon: '/Content/images/add.png',
                        handler: function () {
                            var win = Ext.create("app.prm.document.UploadTagFile", { ProjectId: me.projectId });
                            win.on("savesuccess", function () {
                                me.tagStore.load();
                                me.getTagGrid().store.load();
                                win.close();
                            });
                            win.show();
                        }
                    }
                ],
                viewConfig: {
                    enableTextSelection: true //可以复制单元格文字
                },
                forceFit: true,
                store: store,
                columns: [
                    {
                        header: "名称", dataIndex: 'name', width: 200
                    },
                    { header: '标签', dataIndex: 'tags' },
                    { header: "大小(kb)", dataIndex: 'length' },
                    { header: "类型", dataIndex: 'extension' },
                    {
                        header: "创建时间", dataIndex: 'creationTime', renderer: function (value, p, record) {
                            return Ext.util.Format.date(value, 'Y-m-d');
                        }
                    },
                    {
                        header: "创建人", dataIndex: 'creationUser'
                    },
                    {
                        xtype: 'actioncolumn',
                        minWidth: 120,
                        header: '操作',
                        items: [
                            {
                                iconCls: 'download',
                                tooltip: '下载',
                                handler: function (grid, rowIndex, colIndex) {
                                    var record = grid.store.getAt(rowIndex);
                                    window.location.href = '/api/services/app/document/GetFile?path=' + record.data.fullUrl;
                                }
                            },
                            {
                                icon: '/Content/images/add_tag.gif',
                                tooltip: '设置标签',
                                handler: function (grid, rowIndex, colIndex) {
                                    var record = grid.store.getAt(rowIndex);
                                    var win = Ext.create("app.prm.document.ChooseTag", { Tags: record.data.tags });
                                    win.on("savesuccess", function (tag) {
                                        App.AjaxPost('/api/services/app/document/SetDocumentTag', { documentId: record.data.id, Tag: tag }, function () {
                                            me.tagStore.load();
                                            me.getTagGrid().store.load();
                                        });
                                        win.close();
                                    });
                                    win.show();
                                }
                            },
                            {
                                iconCls: 'delete',
                                tooltip: '删除文档',
                                handler: function (grid, rowIndex, colIndex) {
                                    var record = grid.store.getAt(rowIndex);
                                    if (!record.data.hasDelete) {
                                        return false;
                                    }
                                    App.AjaxDelete('/api/services/app/document/RemoveDocument?documentId=' + record.data.id + "&projectId=" + me.projectId, function () {
                                        me.tagStore.load();
                                        me.getTagGrid().store.load();
                                    });
                                },
                                getClass: function (v, meta, record) {
                                    if (record.data.hasDelete) {
                                        return 'delete';
                                    } else {
                                        return 'x-hidden';
                                    }
                                }
                            }
                        ]
                    }
                ],
                dockedItems: [this.tagGridbbar]
            });
        }
        return this.tagGrid;
    },
    loadGrid: function () {
        var me = this;
        me.gridbbar.moveFirst();

    }
});


(function ($) {

    var methods = {
        _download: function (options) {
            var triggerDelay = (options && options.delay) || 100;
            var removeDelay = (options && options.removeDelay) || 1000;
            this.each(function (index, item) {
                methods._createIFrame(item, index * triggerDelay, removeDelay);
            });
        },
        _createIFrame: function (url, triggerDelay, removeDelay) {
            //动态添加iframe，设置src，然后删除
            setTimeout(function () {
                var frame = $('<iframe style="display: none;" class="multi-download"></iframe>');
                frame.attr('src', url);
                $(document.body).after(frame);
                setTimeout(function () {
                    frame.remove();
                }, removeDelay);
            }, triggerDelay);
        }
    };

    $.fn.multiDownload = function (options) {
        methods._download.apply(this, arguments);
    };

})(jQuery);